<template>
  <div class="contract-business">
    <a-button type="danger" style="margin-right:5px" size="small" @click="allAction('open')">全部开启</a-button>
    <a-button type="primary" style="margin-right:5px" size="small" @click="allAction('stop')">全部停止</a-button>
    <a-button :disabled="selectedRowKeys.length == 0" type="danger" style="margin-right:5px" size="small" @click="batchAction('open')">批量开启</a-button>
    <a-button :disabled="selectedRowKeys.length == 0" type="primary" style="margin-right:5px" size="small" @click="batchAction('stop')">批量停止</a-button>
    <a-button :disabled="selectedRowKeys.length == 0" type="danger" style="margin-right:5px" size="small" @click="onEdit('', 'price')">批量改费用</a-button>
    <a-button :disabled="selectedRowKeys.length == 0" type="primary" style="margin-right:5px" size="small" @click="onEdit('', 'official')">批量改官费</a-button>
    <a-button :disabled="selectedRowKeys.length == 0" type="danger" size="small" @click="onCost">批量设置成本</a-button>
<!--    <a-button type="primary" size="small">批量改付款时间</a-button>-->
    <s-table
      style="margin-top:10px"
      bordered
      ref="table"
      size="middle"
      :row-key="(record) => record.cb_id"
      :columns="businessColumns"
      :data="businessData"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <template slot="business_no" slot-scope="text,record">
        <a-button size="small" type="link" @click="$router.push({ name: 'BusinessDetail', params: { id: record.cb_id } })">{{text}}</a-button>
        <a-button
          size="small"
          type="link"
          icon="copy"
          class="copy"
          :data-clipboard-text="text"
          @click="copy"
        >
        </a-button>
      </template>
      <template slot="additional_content" slot-scope="text, record">
        <div v-if="record.exts.length !== 0">
          <span>1、{{record.exts[0].name}} {{record.exts[0].amount}}</span>
          <a-button type="link" @click="onExtView(record.exts)">查看</a-button>
        </div>
        <div v-else>无</div>
      </template>
      <template slot="price" slot-scope="text,record">
        <a-button icon="edit" type="link" @click="onEdit(record.cb_id,'price')">{{text}}</a-button>
      </template>
      <template slot="official_fee" slot-scope="text,record">
        <a-button icon="edit" type="link" @click="onEdit(record.cb_id,'official')">{{text}}</a-button>
      </template>
      <template slot="cost_fee" slot-scope="text,record">
        <a-button icon="edit" type="link" @click="onEditOfficial(record.cb_id)">{{text}}</a-button>
      </template>
      <template slot="status1" slot-scope="text,record">
        <a-button v-if="text == 10" size="small" icon="edit" type="default" @click="isOpenBusiness(record.cb_id)">{{statusOpts[text]}}</a-button>
        <a-button v-if="text == 20" size="small" icon="edit" type="primary" @click="isOpenBusiness(record.cb_id)">{{statusOpts[text]}}</a-button>
        <a-button v-if="text == 30" size="small" icon="edit" type="danger" @click="isOpenBusiness(record.cb_id)">{{statusOpts[text]}}</a-button>
      </template>
    </s-table>
    <a-modal
      title="费用编辑"
      v-model="amountVisible"
      :width="300"
      :destroy-on-close="true"
      :confirm-loading="loading"
      @ok="submitAmount"
      @cancel="cancelAmount"
    >
      <a-form-model
        ref="priceForm"
        :model="modifyForm"
      >
        <a-form-model-item label="修改的费用">
          <a-input-number
            placeholder="请输入多少官费"
            v-model="modifyForm.price"
            style="width:100%"
            :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
          >
          </a-input-number>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="官费编辑"
      v-model="officialVisible"
      :width="300"
      :destroy-on-close="true"
      :confirm-loading="loading"
      @ok="submitOfficial"
      @cancel="cancelOfficial"
    >
      <a-form-model
        ref="officialForm"
        :model="modifyForm"
      >
        <a-form-model-item label="修改的费用" prop="amount">
          <a-input-number
            placeholder="请输入多少官费"
            v-model="modifyForm.official_fee"
            style="width:100%"
            :formatter="value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\￥\s?|(,*)/g, '')"
          >
          </a-input-number>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <paid-official :business-id="businessId" v-if="paidVisible" @cancel="cancelPaid"></paid-official>
    <a-modal
      centered
      v-model="visible1"
      title="添加已付成本"
      @ok="onSubmitPaid"
      :confirm-loading="loading"
      :width="280"
    >
      <a-form-model
        ref="officialForm"
        :model="costForm"
      >
        <a-form-model-item label="成本" prop="amount">
          <a-input-number
            placeholder="请输入已付成本"
            v-model="costForm.cost_fee"
            style="width:100%"
            :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\$\s?|(,*)/g, '')"
          >
          </a-input-number>
          <a-form-model-item label="付款时间">
            <a-date-picker style="width:100%" @change="onChange" />
          </a-form-model-item>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <ext-view v-if="extVisible" :ext-list="extList" @cancel="onCancelExt"></ext-view>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import { STable } from '@/components'
import financeColumns from '@/columns/finance'

import {
  allOpen,
  allStop,
  batchPrice,
  batchOfficial,
  batchOpen,
  batchStop,
  getBusinessList,
  getIsOpen,
  postIsOpen,
  batchCost
} from '@/api/contract'
import PaidOfficial from './PaidOffical'
import ExtView from '@/views/contract/components/ExtView'

export default {
  components: {
    ExtView,
    STable,
    PaidOfficial
  },
  name: 'Business',
  data () {
    return {
      businessColumns: financeColumns.business,
      businessData: parameters => {
        return getBusinessList(Object.assign(parameters, this.queryParam)).then(res => {
          this.statusOpts = res.result.status1_opts
          return res.result
        })
      },
      queryParam: {},
      statusOpts: {},
      selectedRowKeys: [],
      officialVisible: false,
      paidVisible: false,
      amountVisible: false,
      timeVisible: false,
      modifyForm: {},
      type: '',
      loading: false,
      businessId: '',
      visible1: false,
      costForm: {},
      extList: [],
      extVisible: false
    }
  },
  created () {
    this.queryParam['filter[contract_id]'] = this.$route.params.id
  },
  methods: {
    isOpenBusiness (bid) {
      const app = this
      const data = {}
      data['contract_id'] = this.$route.params.id
      data['cb_id'] = bid
      getIsOpen(data).then(res => {
        if (res.status === 0) {
          this.$confirm({
            title: '是否执行开启/关闭操作',
            onOk: () => {
              postIsOpen(data).then(res => {
                app.$refs.table.refresh()
              })
            }
          })
        } else {
          this.$warning({
            title: res.msg
          })
        }
      })
    },
    allAction (type) {
      const app = this
      if (type === 'open') {
        app.$confirm({
          title: '是否全部开启',
          onOk: () => {
            allOpen(app.$route.params.id).then(res => {
              if (res.status === 0) {
                app.$refs.table.refresh()
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          }
        })
      } else {
        app.$confirm({
          title: '是否全部停止',
          onOk: () => {
            allStop(app.$route.params.id).then(res => {
              if (res.status === 0) {
                app.$refs.table.refresh()
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          }
        })
      }
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    batchAction (type) {
      const app = this
      const parameter = {}
      parameter['contract_id'] = app.$route.params.id
      parameter['ids'] = app.selectedRowKeys
      if (type === 'open') {
        app.$confirm({
          title: '确认批量开启勾选的业务',
          onOk: () => {
            batchOpen(parameter).then(res => {
              app.$refs.table.refresh()
            })
          }
        })
      } else {
        app.$confirm({
          title: '确认批量停止勾选的业务',
          onOk: () => {
            batchStop(parameter).then(res => {
              app.$refs.table.refresh()
            })
          }
        })
      }
    },
    onEditOfficial (id) {
      this.businessId = id
      this.paidVisible = true
    },
    onEdit (id, type) {
      this.type = type
      this.modifyForm['cb_id'] = id
      if (type === 'official') {
        this.officialVisible = true
      }
      if (type === 'price') {
        this.amountVisible = true
      }
    },
    onCost () {
      this.visible1 = true
    },
    onChange (date, dateString) {
      this.costForm.payment_time = dateString
    },
    onSubmitPaid () {
      const app = this
      const param = {}
      app.loading = true
      param['ids'] = app.selectedRowKeys
      batchCost(param, app.costForm).then(res => {
        if (res.status === 0) {
          app.costForm = {}
          app.visible1 = false
          app.loading = false
          app.$refs.table.refresh()
        } else {
          app.$warning({
            title: res.msg
          })
          app.loading = false
        }
      })
    },
    copy () {
      const clipboard = new Clipboard('.copy')
      clipboard.on('success', e => {
        this.$message.success('复制成功')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        this.$message.error('复制失败')
        clipboard.destroy()
      })
    },
    onExtView (ext) {
      this.extList = ext
      this.extVisible = true
    },
    onCancelExt (visible) {
      this.extVisible = visible
    },
    cancelPaid (visible) {
      this.$refs.table.refresh()
      this.paidVisible = visible
    },
    cancelOfficial () {
      this.loading = false
      this.officialVisible = false
      this.$refs.table.refresh(true)
    },
    cancelAmount () {
      this.loading = false
      this.amountVisible = false
      this.modifyForm = {}
      this.$refs.table.refresh()
    },
    submitOfficial () {
      const app = this
      const parameter = {}
      let arr = []
      app.loading = true
      app.$refs.officialForm.validate(valid => {
        if (valid) {
          if (app.selectedRowKeys.length === 0) {
            arr[0] = app.modifyForm.cb_id
          } else {
            arr = app.selectedRowKeys
          }
          parameter['ids'] = arr
          batchOfficial(app.modifyForm, parameter).then(res => {
            if (res.status === 0) {
            } else {
              app.$warning({
                title: res.msg
              })
            }
          }).finally(() => {
            app.$emit('change')
            app.cancelOfficial()
          })
        } else {
          return false
        }
      })
    },
    submitAmount () {
      const app = this
      const parameter = {}
      let arr = []
      app.loading = true
      app.$refs.priceForm.validate(valid => {
        if (valid) {
          if (app.selectedRowKeys.length === 0) {
            arr[0] = app.modifyForm.cb_id
          } else {
            arr = app.selectedRowKeys
          }
          parameter['ids'] = arr
          batchPrice(app.modifyForm, parameter).then(res => {
            if (res.status === 0) {
            } else {
              app.$warning({
                title: res.msg
              })
            }
          }).finally(() => {
            app.$emit('change')
            app.cancelAmount()
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
